/**
 *
 * Copyright 2015 RSVP Technologies Inc. All rights reserved.
 * PlaceSuggestion.java
 *
 */
package com.gfinal.map.suggestion;

import java.util.ArrayList;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gfinal.map.common.Constant;
import com.gfinal.map.util.HttpUtils;
import com.gfinal.map.util.Print;

/**
 * 地名验证
 * @author Gao Yudong (gyd@nbicc.com)
 * @date 2015-2-26
 */
public class PlaceSuggestion {
	private static final String TAG = PlaceSuggestion.class.getName();

	private String query = null;
	private String region = "全国";

	public void setQuery(String query) {
		this.query = query;
	}

	public void setRegion(String region) {
		this.region = region;
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private String createURI() {
		ArrayList params = new ArrayList();
		params.add(new BasicNameValuePair("ak", Constant.BAIDU_AK));
		params.add(new BasicNameValuePair("output", "json"));
		params.add(new BasicNameValuePair("query", query));
		params.add(new BasicNameValuePair("region", region));
		return Constant.PLACE_SUGGESTION_URL + "?"
				+ URLEncodedUtils.format(params, Constant.CHARSET);
	}
	
	public ArrayList<SuggestBean> execute() {
		ArrayList<SuggestBean> suggestList = new ArrayList<SuggestBean>();
		String response = HttpUtils.doGet(createURI());
		JSONObject obj = JSON.parseObject(response);
		if (obj.getIntValue("status") == 0) {
			JSONArray suggestArr = obj.getJSONArray("result");
			for (int i = 0; i < suggestArr.size(); i++) {
				JSONObject sgtObj = (JSONObject) suggestArr.get(i);
				SuggestBean poi = JSON.parseObject(sgtObj.toJSONString(),
						SuggestBean.class);
				suggestList.add(poi);
			}
		}
		return suggestList;
	}
	
	public static void main(String[] args) {
		PlaceSuggestion search = new PlaceSuggestion();
		search.setQuery("书店");
		search.setRegion("宁波市");
		ArrayList<SuggestBean> list = search.execute();
		Print.pln(TAG, list);
	}
}
